import React, { useEffect, useState } from 'react'
import TypeBuilder, { JSONSchema, styles } from '../apps/type_builder'
import { Col, Input, Row } from 'antd'
import { InputStatus } from 'antd/es/_util/statusUtils'

const DemoJSONBuilder = () => {
    const [schema, updateSchema] = useState<JSONSchema>({
        "$schema": "http://json-schema.org/draft-04/schema#",
        "type": "object",
        "properties": {
            "eee": {
                "type": "object",
                "properties": {
                    "field_6": {
                        "type": "string"
                    }
                }
            },
            "field_5": {
                "type": "array",
                "items": {
                    "type": "object",
                    "properties": {}
                }
            }
        }
    })
    const [status, setStatus] = useState<InputStatus>("")
    const [code, setCode] = useState("")

    useEffect(function () {
        try {
            setCode(TypeBuilder({schema}))
        } catch (e) {
            setStatus("error")
        }
    }, [schema])

    const onChange = (txt: string) => {
        try {
            updateSchema(JSON.parse(txt))
        } catch (e) {
            setStatus("error")
        }
    }

    const height = window.screen.height - 300
    return <Row style={{ padding: '20px' }} gutter={[16, 16]}>
        <Col span={12}>
            <Input.TextArea style={{
                height,
            }} status={status} defaultValue={JSON.stringify(schema, null, 2)} onChange={e => onChange(e.target.value)} />
        </Col>
        <Col span={12} style={{
            height,
        }}>
            <pre className={styles.container}><code dangerouslySetInnerHTML={{ __html: code }}></code></pre>
        </Col>
    </Row>
}

export default DemoJSONBuilder